import Vue from 'vue'
import store from '@/store'

// 注册一个全局自定义指令 `v-focus`
// Vue.directive('focus',{
//   // 当被绑定的元素插入到 DOM 中时……
//   inserted:function (el) {
//     // 聚焦元素
//     el.focus()
//   }
// })
//
// export default Vue.directive('focus')

function isAllowed(permission,permissions){
  if (typeof permission === 'string'){
    return  permissions.includes(permission)
  }
  if (permission instanceof Array){
    return permission.some(auth => permissions.indexOf(auth) >= 0)
  }
  return false
}

Vue.directive('permission',{
  // 只调用一次，指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
  bind (el,binding){
    let permission
    let type
    // Object.prototype.toString.call() 返回对象的原型 如[object Object] [object Number]  [object String]
    if (Object.prototype.toString.call(binding.value) == '[object Object]'){
      permission = binding.value.permission
      type = binding.value.type
    } else {
      permission = binding.value
    }
    const isAllow = isAllowed(permission,store.state.permissions)
    const element = el
    if (!isAllow && permission){
      if (type =='disabled') {
        element.disabled = true
        element.style.opacity = 0.4
        element.style.cursor = 'not-allowed'
      } else if (type == 'none') {
        element.style.display = 'none'
      }else {
        element.disabled = true
        element.style.opacity = 0.4
        element.style.cursor = 'not-allowed'
      }
    }

  }
})
export default Vue.directive('permission')
